import logging
import os
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import connection

from apps.vadmin.scripts import getViewSql

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    """ 
    视图初始化命令: python manage.py init_view
    """

    def createView(self,sql_filename,view_name):
        sql = getViewSql(sql_filename)
        with connection.cursor() as cursor:
            logger.info(f'正在初始化[{view_name}]中...')
            try:
                cursor.execute('drop view {};'.format(view_name))
            except Exception as e:
                pass
            try:
                cursor.execute(sql)
            except Exception as e:
                print(e)
            logger.info(f'[{view_name}]初始化完成！')
            connection.commit()
                
    def handle(self, *args, **options):
        view_dict = { 
            'v_assetstatus_report':[os.path.join('views', 'asset_status_report.sql'), 'v_assetstatus_report'],
            'v_asset_now_checkout':[os.path.join('views', 'asset_now_checkout.sql'), 'v_asset_now_checkout'],
            'v_category_total_report':[os.path.join('views', 'category_total_report.sql'), 'v_categorytotal_report'],
            'v_user_checkout_report':[os.path.join('views', 'user_checkout_report.sql'), 'v_usercheckout_report']
        }   
        init_name = options.get('init_name')
        if init_name:
            [self.createView(*view_dict[ele]) for ele in init_name if ele in init_dict]
        else:
            for ele in view_dict.values():
                self.createView(*ele)
